package bookez.model.dao.generic;

import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.exception.ConstraintViolationException;

import bookez.model.exception.DataAccessLayerException;
import bookez.model.exception.DuplicateValueException;


public abstract class GenericDaoHibernateImpl<T, PK extends Serializable> implements GenericDao<T, PK> {	
	
	public GenericDaoHibernateImpl( Class<T> type ) {
		this.type = type;
	}
	
	@SuppressWarnings("unchecked")
	public PK create( T object ) throws DataAccessLayerException {
		try {
			return (PK) getSession().save( object );
		}
		
		catch ( ConstraintViolationException cve ) {
			throw new DuplicateValueException( cve );
		}//end catch ConstraintViolationException
		
		catch ( Exception ex ) {
			throw new DataAccessLayerException( ex );
		}
	}//end method create
	
	@SuppressWarnings("unchecked")
	public T read( PK id ) throws DataAccessLayerException {
		try {
			return (T) getSession().get( type, id );
		}
		catch ( Exception ex ) {
			throw new DataAccessLayerException( ex );
		}
	}//end method read
	
	public void update( T object ) throws DataAccessLayerException {
		try {
			getSession().update( object );
		}
		catch ( Exception ex ) {
			throw new DataAccessLayerException( ex );
		}
	}//end method update
	
	public void delete( T object ) throws DataAccessLayerException {
		try {
			getSession().delete( object );
		}
		catch ( Exception ex ) {
			throw new DataAccessLayerException( ex );
		}
	}//end method delete
	
	
	/****
	 *  PROPERTIES
	 */
	public SessionFactory getSessionFactory() { return sessionFactory; }
	public void 		  setSessionFactory( SessionFactory value) { this.sessionFactory = value; }
	
	public Session getSession() { return getSessionFactory().getCurrentSession(); }
	
	private Class<T> type;
	private SessionFactory sessionFactory;
}//end class GenericDaoImpl
